/* eslint-disable no-param-reassign */
/* eslint-disable no-nested-ternary */
import Toast from 'tdesign-miniprogram/toast/index';
const $api = require('../../../../../utils/request').Api;
Component({
	options: {
		multipleSlots: true,
		addGlobalClass: true,
		styleIsolation: 'shared' // 默认情况
	},
	data: {
		currentlist: '',
	},
	properties: {
		src: {
			type: String,
		},
		title: String,
		show: {
			type: Boolean,
			value: false,
		},
		limitBuyInfo: {
			type: String,
			value: '',
		},
		isStock: {
			type: Boolean,
			value: true,
		},
		limitMaxCount: {
			type: Number,
			value: 999,
		},
		limitMinCount: {
			type: Number,
			value: 1,
		},
		modifiedData: {
			type: Array,
			observer: function (newVal) { // 监听curPath属性变化，若这个值存在，且与即将附在data中的值不同，就满足我们的要求可以进行后续操作啦
				console.log(newVal);
				if (newVal && this.data.currentlist !== newVal) {
					if (newVal) {
						this.setData({
							currentlist: newVal
						})
						this.initData()
					}
				}


				// if (newVal && this.data.currentPath !== newVal) {
				// 	this.setData({
				// 		currentPath: newVal
				// 	})
				// 	this.getAllActivitySites();
				// }
			}
		},
		skuList: {
			type: Array,
			value: [],
			observer(skuList) {
				if (skuList && skuList.length > 0) {
					if (this.initStatus) {
						this.initData();
					}
				}
			},
		},
		specList: {
			type: Array,
			value: [],
			observer(specList) {
				if (specList && specList.length > 0) {
					this.initData();
				}
			},
		},
		outOperateStatus: {
			type: Boolean,
			value: false,
		},
		hasAuth: {
			type: Boolean,
			value: false,
		},
		count: {
			type: Number,
			value: 1,
			observer(count) {
				this.setData({
					buyNum: count,
				});
			},
		},
	},

	initStatus: false,
	selectedSku: {},
	selectSpecObj: {},

	data: {
		buyNum: 1,
		isAllSelectedSku: false,
		dispint: false
	},

	methods: {
		initData() {
			console.log(this.modifiedData);
			const {
				specList
			} = this.properties;
			const {
				skuList
			} = this.properties;
			skuList.forEach((item) => {
				if (item.specInfo.length > 0) {
					item.specInfo.forEach((subItem) => {
						subItem.attr_list.forEach((listitem) => {
							console.log(subItem);
							const obj = this.checkSkuStockQuantity(listitem.attr_id, specList);
							listitem.hasStockObj = obj;
							console.log(listitem);
						})

					});
				}
			});
			const selectedSku = {};
			specList.forEach((item) => {
				console.log(item);
				selectedSku[item.attr_group_id] = '';
			});
			this.setData({
				skuList,
			});
			this.selectSpecObj = {};
			this.selectedSku = {};
			this.initStatus = true;
		},

		checkSkuStockQuantity(specValueId, skuList) {
			console.log(specValueId);
			console.log(this.data.currentlist);
			let hasStock = false;
			const array = [];
			skuList.forEach((item) => {
				console.log(item);
				(item.attr_list || []).forEach((subItem) => {
					// console.log(subItem);
					if (subItem.attr_id === specValueId) {
						// console.log('sssssssssssssssssssssssssssss');
						const subArray = [];
						(item.attr_list || []).forEach((specItem) => {
							console.log(specItem);
							subArray.push(specItem.attr_id);
						});
						array.push(subArray);
						if (this.data.currentlist.length > 0) {
							this.data.currentlist.forEach((item, index) => {
								console.log(subItem);
								if (subItem.attr_name === item.attrName) {
									console.log(item);
									subItem.status = true;
								}
							})
						} else {
							hasStock = true;
						}
					}
				});
			});
			console.log(skuList);
			return {
				hasStock,
				specsArray: array,
			};
		},

		chooseSpecValueId(specValueId, specId) {
			console.log(specValueId);
			const {
				selectSpecObj
			} = this;
			const {
				skuList,
				specList
			} = this.properties;
			if (selectSpecObj[specId]) {
				selectSpecObj[specId] = [];
				this.selectSpecObj = selectSpecObj;
			} else {
				selectSpecObj[specId] = [];
			}

			const itemAllSpecArray = [];
			const itemUnSelectArray = [];
			const itemSelectArray = [];
			specList.forEach((item) => {
				console.log(item);
				if (item.specId === specId) {
					const subSpecValueItem = item.specValueList.find((subItem) => subItem.specValueId === specValueId);
					let specSelectStatus = false;
					item.specValueList.forEach((n) => {
						itemAllSpecArray.push(n.hasStockObj.specsArray);
						if (n.isSelected) {
							specSelectStatus = true;
						}
						if (n.hasStockObj.hasStock) {
							itemSelectArray.push(n.specValueId);
						} else {
							itemUnSelectArray.push(n.specValueId);
						}
					});
					if (specSelectStatus) {
						selectSpecObj[specId] = this.flatten(subSpecValueItem?.hasStockObj.specsArray.concat(itemSelectArray));
					} else {
						const subSet = function (arr1, arr2) {
							const set2 = new Set(arr2);
							const subset = [];
							arr1.forEach((val) => {
								if (!set2.has(val)) {
									subset.push(val);
								}
							});
							return subset;
						};
						selectSpecObj[specId] = subSet(this.flatten(itemAllSpecArray), this.flatten(itemUnSelectArray));
					}
				} else {
					// 未点击规格的逻辑
					const itemSelectArray = [];
					let specSelectStatus = false;
					item.attr_list.map(
						// 找到有库存的规格数组
						(n) => {
							console.log(n);
							itemSelectArray.push(n.hasStockObj.specsArray);
							if (n.isSelected) {
								specSelectStatus = true;
							}
							n.hasStockObj.hasStock = true;
							return n;
						},
					);
					if (specSelectStatus) {
						selectSpecObj[item.specId] = this.flatten(itemSelectArray);
					} else {
						delete selectSpecObj[item.specId];
					}
				}
				this.selectSpecObj = selectSpecObj;
			});
			const combatArray = Object.values(selectSpecObj);
			if (combatArray.length > 0) {
				const showArray = combatArray.reduce((x, y) => this.getIntersection(x, y));
				const lastResult = Array.from(new Set(showArray));
				specList.forEach((item) => {
					item.specValueList.forEach((subItem) => {
						console.log(subItem);
						if (lastResult.includes(subItem.specValueId)) {
							subItem.hasStockObj.hasStock = true;
						} else {
							subItem.hasStockObj.hasStock = false;
						}
					});
				});
			} else {
				specList.forEach((item) => {
					if (item.specValueList.length > 0) {
						item.specValueList.forEach((subItem) => {
							const obj = this.checkSkuStockQuantity(subItem.specValueId, skuList);
							subItem.hasStockObj = obj;
							console.log(obj);
						});
					}
				});
			}
			this.setData({
				specList,
			});
		},

		flatten(input) {
			const stack = [...input];
			const res = [];
			while (stack.length) {
				const next = stack.pop();
				if (Array.isArray(next)) {
					stack.push(...next);
				} else {
					res.push(next);
				}
			}
			return res.reverse();
		},

		getIntersection(array, nextArray) {
			return array.filter((item) => nextArray.includes(item));
		},

		// toChooseItem(e) {
		// 	console.log(e);
		// 	const {
		// 		isStock
		// 	} = this.properties;
		// 	if (!isStock) return;
		// 	const {
		// 		id
		// 	} = e.currentTarget.dataset;
		// 	const specId = e.currentTarget.dataset.specId;
		// 	const hasStock = e.currentTarget.dataset.hasstock;
		// 	if (hasStock) {
		// 		Toast({
		// 			context: this,
		// 			selector: '#t-toast',
		// 			message: '该规格已售罄',
		// 			icon: '',
		// 			duration: 1000,
		// 		});
		// 		return;
		// 	}

		// 	let {
		// 		selectedSku
		// 	} = this;
		// 	const {
		// 		specList
		// 	} = this.properties;
		// 	selectedSku =
		// 		selectedSku[specId] === id ? {
		// 			...this.selectedSku,
		// 			[specId]: ''
		// 		} : {
		// 			...this.selectedSku,
		// 			[specId]: id
		// 		};
		// 	specList.forEach((item) => {
		// 		console.log(item);
		// 		item.attr_list.forEach((valuesItem) => {
		// 			if (item.attr_group_id === specId) {
		// 				console.log(item.attr_group_id, specId);
		// 				valuesItem.isSelected = valuesItem.attr_id === selectedSku[specId];
		// 			}
		// 		});
		// 	});
		// 	this.chooseSpecValueId(id, specId);
		// 	const isAllSelectedSku = this.isAllSelected(specList, selectedSku);
		// 	if (!isAllSelectedSku) {
		// 		this.setData({
		// 			selectSkuSellsPrice: 0,
		// 			selectSkuImg: '',
		// 		});
		// 	}
		// 	this.setData({
		// 		skuList,
		// 		isAllSelectedSku,
		// 	});
		// 	this.selectedSku = selectedSku;
		// 	this.triggerEvent('change', {
		// 		skuList,
		// 		selectedSku,
		// 		isAllSelectedSku,
		// 	});
		// },


		toChooseItem(e) {
			console.log(e);
			const {
				isStock
			} = this.properties;
			if (!isStock) return;
			const {
				id
			} = e.currentTarget.dataset;
			const specId = e.currentTarget.dataset.specid;
			const hasStock = e.currentTarget.dataset.hasstock;
			if (hasStock) {
				Toast({
					context: this,
					selector: '#t-toast',
					message: '该规格已售罄',
					icon: '',
					duration: 1000,
				});
				return;
			}
			let {
				selectedSku
			} = this;
			selectedSku =
				selectedSku[specId] === id ? {
					...this.selectedSku,
					[specId]: ''
				} : {
					...this.selectedSku,
					[specId]: id
				};
			console.log(selectedSku);
			this.data.skuList[0].specInfo.forEach((item, index) => {
				console.log(index);
				console.log(item);
				item.attr_list.forEach((xitem) => {
					if (item.attr_group_id === specId) {
						console.log(item, specId);
						xitem.isSelected = xitem.attr_id === selectedSku[specId];
					}
				})
			})
			// this.chooseSpecValueId(id, specId);
			const isAllSelectedSku = this.isAllSelected(this.data.skuList[0].specInfo, selectedSku);
			console.log(selectedSku);
			if (!isAllSelectedSku) {
				this.setData({
					selectSkuSellsPrice: 0,
					selectSkuImg: '',
				});
			}
			this.setData({
				skuList: this.data.skuList,
				isAllSelectedSku,
			})
			this.setData({
				skuList: this.data.skuList,
				isAllSelectedSku,
			});
			this.selectedSku = selectedSku;
			this.triggerEvent('change', {
				skuList: this.data.skuList,
				selectedSku: selectedSku,
				isAllSelectedSku,
			});
		},
		// 判断是否所有的sku都已经选中
		isAllSelected(skuTree, selectedSku) {
			console.log(skuTree);
			const selected = Object.keys(selectedSku).filter((skuKeyStr) => selectedSku[skuKeyStr] !== '');
			return skuTree.length === selected.length;
		},

		handlePopupHide() {
			this.triggerEvent('closeSpecsPopup', {
				show: false,
			});
		},

		specsConfirm() {
			const {
				isStock
			} = this.properties;
			if (!isStock) return;
			let list = [{
				buyNum: this.data.buyNum
			}]
			this.triggerEvent('specsConfirm', list);
		},

		addCart() {
			let userInfo = wx.getStorageSync('userInfo')
			if (userInfo == '') {
				wx.navigateTo({
					url: '/pages/usercenter/userAuthorized/Authorized'
				});
			} else {
				const {
					isStock
				} = this.properties;
				if (!isStock) return;
				this.triggerEvent('addCart');
				// $api.addShoppingCart({
				// 	attribute
				// 	goodsId
				// 	price
				// 	productSize
				// 	sizeId
				// 	sizeName
				// 	useId
				// 	wxUid
				// 	yuanPrice
				// 	goodsNum
				// }).then((res) => {

				// })
			}
		},

		buyNow() {
			console.log();
			const {
				isAllSelectedSku
			} = this.data;
			const {
				isStock
			} = this.properties;
			if (!isStock) return;
			this.triggerEvent('buyNow', {
				isAllSelectedSku,
			});
		},

		// 总处理
		setBuyNum(buyNum) {
			this.setData({
				buyNum,
			});
			this.triggerEvent('changeNum', {
				buyNum,
			});
		},

		handleBuyNumChange(e) {
			console.log(e);
			const value = e.detail;
			this.triggerEvent('changeNum', {
				buyNum: e.detail,
			});
			this.setData({
				buyNum: value,
			});
			console.log(this.data.buyNum);
		},
		// focus(e) {
		// 	console.log(e);
		// }
	},
});